package com.ruoyi.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.web.feign.FeginDemo;
import com.ruoyi.web.feign.Response;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
@SaIgnore
@RestController
@RequestMapping("/demo")
public class FeignDemoController {

    final
    FeginDemo feginDemo;

    public FeignDemoController(FeginDemo feginDemo) {
        this.feginDemo = feginDemo;
    }

    private static final String publicPem = """
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxfDKI3ZXpqTnhz4K1s3h
    +LoGiuKeFXRlmk13H7wZwpsoKUGbqi5c7tzoSiCIVuM/U+IgjG3J0g5PxzRbP++I
    GPOz7PMXS2+iiiubPwsuVTpJbNPPT1Cts7GaXIpeHMoNJtnQ2mFiRtj/UDDi+Lih
    y4QODQOYZ1zdlv24HuUlJqCtkT0NvWzQoeTyGNMUTDlVkaLCqtsaV19O7KZrdwCD
    VC1+v/2KbcGpBYIVW2Y70x7BCnxUzlH0YBl28eYwF5qKdkfLqQzZT8mxZI3gbP0w
    tSCw4NGiDtpKA31uVs94KrO7w33HKaYxDIQie0CMUtFoG3970N6msXanFaaqhCom
    tQIDAQAB
    """;

    private String token = "";
    public static String bytesToHexFun3(byte[] bytes) {
        var buf = new StringBuilder(bytes.length * 2);
        for(byte b : bytes) { // 使用String的format方法进行转换
            buf.append(String.format("%02x", Integer.valueOf(b & 0xff)));
        }

        return buf.toString();
    }

    //加密
    public static String getEncryptString(String str, RSA rsa){
        var encrypt = rsa.encrypt(StrUtil.bytes(str, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
        // 传 Base64
//        return Base64.getEncoder().encodeToString(encrypt);
        // 传 16进制字符串
        return bytesToHexFun3(encrypt);
    }

    @GetMapping("/login")
    public Map<String, Object> login() {
        var map = new HashMap<String, Object>();
        map.put("Username", "admin");
        var pubicPemWithTrim = publicPem.trim();
        var rsa = new RSA(null, pubicPemWithTrim);
        var password = getEncryptString("123456", rsa);
        map.put("Password", password);
        var test = feginDemo.login(map, true);
        try {
            var objectMapper = new ObjectMapper();
            var res = objectMapper.readValue(test, Response.class);
            token = res.Data.toString();
        } catch (Exception e) {
            System.out.println(e);
        }
//        var header = new HashMap<String, Object>();
//        header.put("Authorization", token);
        return feginDemo.userGetInfo(2, "Bearer " + token);
    }

//    @GetMapping("")
}
